﻿using System;
using System.IO;

namespace Library.Gsm.AtCommands {
  public class SendSmsCommand : BaseAtCommand {
    private string _receiver;
    private string _message;
    private class SendMsgContainCommand : SendSmsCommand {
      protected override string GetCommandText(params object[] t) {
        return String.Format("{0}", t[0]);
      }
      public override OneLineStringCollection ParseResponse(string response, IGsmCommand gsmCommand) {
        return ReadToEndOk(response);
      }
      public override string AtCommandText {
        get {
          return UserCommandText + (char)0x1A;
        }
      }

      protected override bool AddLine(OneLineStringCollection lines, string line) {
        if (String.IsNullOrEmpty(line)) return false;
        if (line == AtCommandText) return false;
        lines.Add(line.Trim());
        return true;
      }

      public override int Instance {
        get { return 2; }
      }
    }

    protected virtual string NewLine { get { return ">"; } }
    protected override string GetCommandText(params object[] t) {
      _receiver = t[0].ToString();
      _message = t[1].ToString();
      return String.Format("AT+CMGS=\"{0}\"", _receiver);
    }
    public override OneLineStringCollection ParseResponse(string response, IGsmCommand gsmCommand) {
      var result = ReadToEndNewLine(response);
      if (result.FirstLine != NewLine)
        throw new UnknowResponseException(result.ToString()) { CommandText = AtCommandText };
      var body = new SendMsgContainCommand();
      body.CreateCommandText(_message);
      var collection = gsmCommand.Execute(body);
      return collection;
    }

   

    protected OneLineStringCollection ReadToEndNewLine(string reponse) {
      var result = new OneLineStringCollection();
      var reader = new StringReader(reponse);
      var line = reader.ReadLine();
      while (line != null) {
        if (line == NewLine) {
          var nextLine = reader.ReadLine();
          if (nextLine == null)
            return result;
          AddLine(result, line);

          line = nextLine;
        } else {
          AddLine(result, line);
          line = reader.ReadLine();
        }
      }

      return result;
    }
  }
}
